package com.demo.user.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 手动注入bean
 *
 * @author
 * 我发现当前类含有@Autowired注入Spring Bean的成员对象时候，则当前类必须也是Spring Bean才能调用它，也就是说该类必须写上注解@Component、@Configuration加入
 * Spring Bean管理该类。然后运用时候通过@Resource或者@Autowired来注入Bean，这样才能调用该类的某bean成员对象的方法，不能用newxxx()来获得对象，
 * 这种方式获得的对象无法调用@Autowired注入的Bean成员对象的方法。
 */
@Component
public final class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static final Logger log = LoggerFactory.getLogger(ApplicationContextUtil.class);
    /**
    * Description: get a bean from Spring context by type
    * 通过class获取Bean.
    * @param clz
    * @return
    */
    public static <T> T getBean(Class<T> clz) {
    	if(applicationContext==null){
    		log.debug("applicationContext is null");
    		return null;
    	}
    	else{
    		log.info("applicationContext this class "+clz.getName());
    		return applicationContext.getBean(clz);
    	}
        
    }

    /**
     * 通过name获取 Bean
     * @param name
     * @return
     * @param <T>
     */
    public static <T> T getBean(String name) {
        if (applicationContext == null) {
            log.debug("applicationContext is null");
            return null;
        } else {
            log.info("applicationContext this class " + name);
            return (T) applicationContext.getBean(name);
        }
    }

    /**
    * Description: get a bean from Spring context by type and qualifier
    * 通过name,以及Clazz返回指定的Bean
    * @param name
    * @param clz
    * @return
    */
    public static <T> T getBean(String name, Class<T> clz) {
        return applicationContext.getBean(name, clz);
    }

    /**
     * 插入ApplicationContext
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) {
        ApplicationContextUtil.applicationContext = applicationContext; // NOSONAR
    }

    /**
     * 获取ApplicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

}
